// pages/game/game.js
Page({
  data: {
    score: 0,
    highScore: 0,
    gameOver: false,
    isPlaying: false,
    countdown: 0,
    grid: [], // 游戏网格
    gridSize: 8, // 8x8网格
    cellSize: 0, // 单元格大小，将根据屏幕大小计算
    imageUrls: [
      '/images/tabbar/sad.jpg',
      '/images/tabbar/home.png',
      '/images/tabbar/history.png',
      '/images/tabbar/stats.png',
      '/images/tabbar/profile.png'
    ], // 方块图片
    imagesLoaded: false, // 图片是否已加载
    selectedCell: null, // 当前选中的方块
    animations: [], // 消除动画
    screenWidth: 375,
    screenHeight: 600,
    timeLeft: 60, // 游戏时间（秒）
    comboCount: 0, // 连击次数
    showCombo: false, // 是否显示连击提示
    comboBonus: 0, // 连击奖励分数
    maxCombo: 0, // 最大连击数
    // 拖拽相关状态
    isDragging: false, // 是否正在拖拽
    dragStartCell: null, // 拖拽开始的方块
    dragCurrentCell: null, // 当前拖拽到的方块
    touchStartX: 0, // 触摸开始的X坐标
    touchStartY: 0, // 触摸开始的Y坐标
    touchStartTime: 0, // 触摸开始时间
    isClickEvent: false, // 是否为点击事件
    clickRow: 0, // 点击的行
    clickCol: 0, // 点击的列
    // 退出确认相关
    showExitConfirm: false, // 是否显示退出确认
  },

  onLoad: function() {
    // 获取系统信息以适应不同屏幕尺寸
    const systemInfo = wx.getSystemInfoSync();
    const screenWidth = systemInfo.windowWidth;
    const cellSize = Math.floor((screenWidth - 20) / this.data.gridSize);
    
    this.setData({
      screenWidth: screenWidth,
      screenHeight: systemInfo.windowHeight,
      cellSize: cellSize
    });

    // 读取历史最高分
    const highScore = wx.getStorageSync('matchHighScore') || 0;
    this.setData({ highScore });
    
    // 预加载图片
    this.preloadImages();
    
    // 添加调试信息
    console.log('游戏初始化完成，图片列表:', this.data.imageUrls);
    
    // 添加游戏版本号，用于跟踪修复
    console.log('一二布布消消乐 v1.1.0 - 修复初始匹配问题');

    // 设置页面退出监听
    this.setupPageExit();
  },
  
  // 设置页面退出监听
  setupPageExit: function() {
    // 监听返回按键事件
    wx.onAppRoute((route) => {
      if (route.action === 'navigateBack' && this.data.isPlaying) {
        // 阻止默认返回行为
        wx.showModal({
          title: '确认退出',
          content: '游戏正在进行中，确认要退出吗？',
          confirmText: '退出',
          cancelText: '继续游戏',
          success: (res) => {
            if (res.confirm) {
              // 用户确认退出，清理游戏状态
              this.forceExitGame();
              wx.navigateBack();
            }
          }
        });
        return false; // 阻止默认返回
      }
    });
  },
  
  // 处理返回按键点击
  onBackPress: function() {
    if (this.data.isPlaying) {
      // 游戏进行中，显示确认对话框
      wx.showModal({
        title: '确认退出',
        content: '游戏正在进行中，确认要退出吗？',
        confirmText: '退出',
        cancelText: '继续游戏',
        success: (res) => {
          if (res.confirm) {
            // 用户确认退出，清理游戏状态
            this.forceExitGame();
            wx.navigateBack();
          }
        }
      });
      return false; // 阻止默认返回
    }
    return true; // 允许返回
  },
  
  // 强制退出游戏
  forceExitGame: function() {
    // 清理所有定时器
    if (this.gameTimer) {
      clearInterval(this.gameTimer);
      this.gameTimer = null;
    }
    
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
      this.countdownTimer = null;
    }
    
    // 重置游戏状态
    this.setData({
      isPlaying: false,
      gameOver: false,
      countdown: 0
    });
  },
  
  // 本地图片不需要预加载
  preloadImages: function() {
    // 直接设置图片已加载
    this.setData({ imagesLoaded: true });
    wx.hideLoading();
  },

  startGame: function() {
    console.log('开始新游戏');
    
    // 首先清除所有存在的定时器，防止重复创建
    if (this.gameTimer) {
      clearInterval(this.gameTimer);
      this.gameTimer = null;
    }
    
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
      this.countdownTimer = null;
    }
    
    // 开始倒计时
    this.setData({
      countdown: 3,
      score: 0,
      gameOver: false,
      isPlaying: false, // 在倒计时期间设为false
      timeLeft: 60,
      comboCount: 0,
      showCombo: false,
      comboBonus: 0,
      maxCombo: 0,
      imagesLoaded: true, // 确保图片已加载标志为true
      selectedCell: null, // 清除选中状态
      isDragging: false,
      dragStartCell: null,
      dragCurrentCell: null
    });

    console.log('开始倒计时');
    this.countdownTimer = setInterval(() => {
      const countdown = this.data.countdown - 1;
      console.log('倒计时:', countdown);
      this.setData({ countdown });
      
      if (countdown <= 0) {
        console.log('倒计时结束，开始游戏');
        clearInterval(this.countdownTimer);
        this.countdownTimer = null;
        this.setData({ isPlaying: true });
        
        // 创建一个确保无匹配的网格
        this.createNoMatchGrid();
        
        this.startGameTimer();
      }
    }, 1000);
  },
  
  // 创建一个确保无匹配的网格
  createNoMatchGrid: function() {
    console.log("创建无匹配网格...");
    
    // 创建网格并立即检查
    this.initGrid(true);
    
    // 强制检查网格中的匹配
    const matches = this.findMatches(this.data.grid);
    if (matches.length > 0) {
      console.log("初始网格仍有匹配，尝试直接修复...", matches);
      
      // 创建一个完全手动的网格，确保没有匹配
      this.createManualGrid();
    } else {
      console.log("成功创建无匹配网格");
    }
  },
  
  // 创建一个完全手动的网格，确保没有匹配
  createManualGrid: function() {
    const { gridSize, imageUrls } = this.data;
    let grid = [];
    
    // 创建一个更安全的交替模式网格，确保没有三个相同的图标连在一起
    for (let i = 0; i < gridSize; i++) {
      let row = [];
      for (let j = 0; j < gridSize; j++) {
        // 使用更复杂的模式来确保相邻位置不会有相同图片
        // 基于棋盘模式，但确保不会产生三连
        let imageIndex = (i * 3 + j * 2) % imageUrls.length;
        
        // 额外检查：如果当前索引可能导致匹配，选择不同的索引
        let attempts = 0;
        while (attempts < imageUrls.length) {
          let hasConflict = false;
          
          // 检查水平冲突
          if (j >= 2 && row[j-1] && row[j-2] && 
              row[j-1].imageIndex === imageIndex && 
              row[j-2].imageIndex === imageIndex) {
            hasConflict = true;
          }
          
          // 检查垂直冲突
          if (i >= 2 && grid[i-1] && grid[i-2] && 
              grid[i-1][j] && grid[i-2][j] &&
              grid[i-1][j].imageIndex === imageIndex && 
              grid[i-2][j].imageIndex === imageIndex) {
            hasConflict = true;
          }
          
          if (!hasConflict) {
            break;
          }
          
          // 尝试下一个索引
          imageIndex = (imageIndex + 1) % imageUrls.length;
          attempts++;
        }
        
        row.push({
          imageUrl: imageUrls[imageIndex],
          imageIndex: imageIndex,
          row: i,
          col: j,
          id: `cell-${i}-${j}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
        });
      }
      grid.push(row);
    }
    
    // 再次检查是否有匹配
    const matches = this.findMatches(grid);
    if (matches.length > 0) {
      console.log("手动网格仍有匹配，进行最终修复...");
      
      // 对每个匹配，直接修改为不会导致匹配的图片
      for (let match of matches) {
        const { row, col } = match;
        if (grid[row] && grid[row][col]) {
          // 找出周围已使用的图片索引
          let usedIndices = new Set();
          
          // 检查水平方向
          if (col > 0 && grid[row][col-1]) {
            usedIndices.add(grid[row][col-1].imageIndex);
          }
          if (col < gridSize - 1 && grid[row][col+1]) {
            usedIndices.add(grid[row][col+1].imageIndex);
          }
          
          // 检查垂直方向
          if (row > 0 && grid[row-1] && grid[row-1][col]) {
            usedIndices.add(grid[row-1][col].imageIndex);
          }
          if (row < gridSize - 1 && grid[row+1] && grid[row+1][col]) {
            usedIndices.add(grid[row+1][col].imageIndex);
          }
          
          // 选择一个未使用的图片索引
          let availableIndices = [];
          for (let i = 0; i < imageUrls.length; i++) {
            if (!usedIndices.has(i)) {
              availableIndices.push(i);
            }
          }
          
          // 如果有可用的索引，随机选择一个
          if (availableIndices.length > 0) {
            const newIndex = availableIndices[Math.floor(Math.random() * availableIndices.length)];
            grid[row][col].imageIndex = newIndex;
            grid[row][col].imageUrl = imageUrls[newIndex];
          } else {
            // 如果没有可用的索引，选择一个与当前不同的索引
            let newIndex;
            do {
              newIndex = Math.floor(Math.random() * imageUrls.length);
            } while (newIndex === grid[row][col].imageIndex);
            
            grid[row][col].imageIndex = newIndex;
            grid[row][col].imageUrl = imageUrls[newIndex];
          }
        }
      }
    }
    
    this.setData({ grid });
    
    // 最终检查
    setTimeout(() => {
      const finalMatches = this.findMatches(this.data.grid);
      if (finalMatches.length > 0) {
        console.log("警告：网格仍然有匹配，但将继续游戏", finalMatches);
      } else {
        console.log("最终网格检查通过，没有匹配");
      }
    }, 100);
  },
  
  // 检查并修复初始网格中的匹配
  checkAndFixInitialGrid: function() {
    const matches = this.findMatches(this.data.grid);
    if (matches.length > 0) {
      console.log('初始网格有匹配，正在修复...', matches);
      
      // 显示调试信息
      this.debugGrid(this.data.grid, matches);
      
      // 创建一个全新的网格，确保没有匹配
      this.initGrid(true); // 传入true表示强制创建无匹配的网格
      
      // 再次检查，确保没有匹配
      setTimeout(() => {
        const newMatches = this.findMatches(this.data.grid);
        if (newMatches.length > 0) {
          console.log('重新初始化后仍有匹配，尝试修复...', newMatches);
          this.debugGrid(this.data.grid, newMatches);
          
          // 使用修复函数
          const fixedGrid = this.fixInitialMatches(this.data.grid);
          this.setData({ grid: fixedGrid });
          
          // 最后检查
          setTimeout(() => {
            const finalMatches = this.findMatches(this.data.grid);
            if (finalMatches.length > 0) {
              console.log('所有修复尝试失败，将继续游戏...');
            } else {
              console.log('修复成功，网格现在没有匹配');
            }
          }, 100);
        } else {
          console.log('重新初始化成功，网格没有匹配');
        }
      }, 100);
    }
  },
  
  // 调试函数：打印网格和匹配信息
  debugGrid: function(grid, matches) {
    if (!grid || !Array.isArray(grid)) return;
    
    console.log('网格大小:', grid.length, 'x', grid[0].length);
    
    // 打印匹配信息
    console.log('匹配数量:', matches.length);
    matches.forEach((match, index) => {
      const { row, col } = match;
      if (grid[row] && grid[row][col]) {
        console.log(`匹配 ${index+1}: 位置(${row},${col}), 图片索引: ${grid[row][col].imageIndex}`);
      }
    });
    
    // 检查水平匹配
    for (let i = 0; i < grid.length; i++) {
      if (!grid[i]) continue;
      
      for (let j = 0; j < grid[i].length - 2; j++) {
        if (grid[i][j] && grid[i][j+1] && grid[i][j+2] &&
            typeof grid[i][j].imageIndex === 'number' &&
            typeof grid[i][j+1].imageIndex === 'number' &&
            typeof grid[i][j+2].imageIndex === 'number' &&
            grid[i][j].imageIndex === grid[i][j+1].imageIndex &&
            grid[i][j].imageIndex === grid[i][j+2].imageIndex) {
          console.log(`发现水平匹配: 行${i}, 列${j}-${j+2}, 图片索引: ${grid[i][j].imageIndex}`);
        }
      }
    }
    
    // 检查垂直匹配
    for (let j = 0; j < (grid[0] ? grid[0].length : 0); j++) {
      for (let i = 0; i < grid.length - 2; i++) {
        if (grid[i] && grid[i+1] && grid[i+2] &&
            grid[i][j] && grid[i+1][j] && grid[i+2][j] &&
            typeof grid[i][j].imageIndex === 'number' &&
            typeof grid[i+1][j].imageIndex === 'number' &&
            typeof grid[i+2][j].imageIndex === 'number' &&
            grid[i][j].imageIndex === grid[i+1][j].imageIndex &&
            grid[i][j].imageIndex === grid[i+2][j].imageIndex) {
          console.log(`发现垂直匹配: 列${j}, 行${i}-${i+2}, 图片索引: ${grid[i][j].imageIndex}`);
        }
      }
    }
  },

  initGrid: function(forceNoMatches = false) {
    const { gridSize, imageUrls } = this.data;
    let grid = [];
    let hasMatches = true;
    let attempts = 0;
    const maxAttempts = forceNoMatches ? 50 : 20; // 如果强制无匹配，增加尝试次数
    
    // 尝试创建没有初始匹配的网格
    while (hasMatches && attempts < maxAttempts) {
      attempts++;
      grid = [];
      
      // 创建初始网格
      for (let i = 0; i < gridSize; i++) {
        let row = [];
        for (let j = 0; j < gridSize; j++) {
          // 随机选择图片，但避免创建匹配
          let imageIndex;
          let validIndices = [...Array(imageUrls.length).keys()]; // 所有可能的索引
          
          // 检查水平方向：避免与前一个和前两个方块形成三连
          if (j >= 1 && row[j-1] && typeof row[j-1].imageIndex === 'number') {
            validIndices = validIndices.filter(idx => idx !== row[j-1].imageIndex);
          }
          if (j >= 2 && row[j-1] && row[j-2] && 
              typeof row[j-1].imageIndex === 'number' && 
              typeof row[j-2].imageIndex === 'number' && 
              row[j-1].imageIndex === row[j-2].imageIndex) {
            // 如果前两个方块相同，避免使用相同的图片
            validIndices = validIndices.filter(idx => idx !== row[j-1].imageIndex);
          }
          
          // 检查垂直方向：避免与上一个和上两个方块形成三连
          if (i >= 1 && grid[i-1] && grid[i-1][j] && typeof grid[i-1][j].imageIndex === 'number') {
            validIndices = validIndices.filter(idx => idx !== grid[i-1][j].imageIndex);
          }
          if (i >= 2 && grid[i-1] && grid[i-2] && 
              grid[i-1][j] && grid[i-2][j] && 
              typeof grid[i-1][j].imageIndex === 'number' && 
              typeof grid[i-2][j].imageIndex === 'number' && 
              grid[i-1][j].imageIndex === grid[i-2][j].imageIndex) {
            // 如果上方两个方块相同，避免使用相同的图片
            validIndices = validIndices.filter(idx => idx !== grid[i-1][j].imageIndex);
          }
          
          // 如果没有有效的索引，使用任意索引
          if (validIndices.length === 0) {
            imageIndex = Math.floor(Math.random() * imageUrls.length);
          } else {
            // 从有效索引中随机选择
            imageIndex = validIndices[Math.floor(Math.random() * validIndices.length)];
          }
          
          row.push({
            imageUrl: imageUrls[imageIndex],
            imageIndex: imageIndex,
            row: i,
            col: j,
            id: `cell-${i}-${j}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}` // 确保ID唯一
          });
        }
        grid.push(row);
      }
      
      // 检查是否有匹配
      const matches = this.findMatches(grid);
      hasMatches = matches.length > 0;
      
      if (hasMatches && forceNoMatches) {
        console.log(`尝试 ${attempts}/${maxAttempts}: 仍有匹配，重新生成...`);
      }
    }
    
    // 如果尝试多次后仍有匹配，手动修复匹配
    if (hasMatches) {
      console.log(`尝试 ${maxAttempts} 次后仍有匹配，使用修复函数...`);
      grid = this.fixInitialMatches(grid);
    }
    
    // 确保有可行的移动
    if (!this.hasValidMoves(grid)) {
      // 如果没有可行的移动，重新生成网格
      console.log('没有可行的移动，重新生成网格');
      return this.initGrid(forceNoMatches);
    }
    
    this.setData({ grid });
    return grid;
  },
  
  // 手动修复初始匹配
  fixInitialMatches: function(grid) {
    if (!grid || !Array.isArray(grid)) return grid;
    
    const { imageUrls } = this.data;
    let matches = this.findMatches(grid);
    let fixAttempts = 0;
    const maxFixAttempts = 50; // 防止无限循环
    
    // 对每个匹配，修改方块
    while (matches.length > 0 && fixAttempts < maxFixAttempts) {
      fixAttempts++;
      
      // 找出所有匹配的方块
      let matchedCells = {};
      matches.forEach(match => {
        const key = `${match.row}-${match.col}`;
        matchedCells[key] = match;
      });
      
      // 找出匹配组
      let matchGroups = this.findMatchGroups(matches);
      
      // 对每个匹配组，修改一个方块
      matchGroups.forEach(group => {
        if (group.length >= 3) {
          // 选择中间的方块进行修改
          const middleIndex = Math.floor(group.length / 2);
          const match = group[middleIndex];
          const row = match.row;
          const col = match.col;
          
          if (grid[row] && grid[row][col]) {
            const currentIndex = grid[row][col].imageIndex;
            
            // 找出不会导致新匹配的图片索引
            let validIndices = [...Array(imageUrls.length).keys()]; // 所有可能的索引
            validIndices = validIndices.filter(idx => idx !== currentIndex); // 排除当前索引
            
            // 检查水平方向
            if (col > 0 && col < grid[row].length - 1) {
              if (grid[row][col-1] && grid[row][col+1] && 
                  typeof grid[row][col-1].imageIndex === 'number' && 
                  typeof grid[row][col+1].imageIndex === 'number') {
                // 如果左右两侧方块相同，排除该索引
                if (grid[row][col-1].imageIndex === grid[row][col+1].imageIndex) {
                  validIndices = validIndices.filter(idx => idx !== grid[row][col-1].imageIndex);
                }
              }
            }
            
            // 检查垂直方向
            if (row > 0 && row < grid.length - 1) {
              if (grid[row-1] && grid[row+1] && 
                  grid[row-1][col] && grid[row+1][col] && 
                  typeof grid[row-1][col].imageIndex === 'number' && 
                  typeof grid[row+1][col].imageIndex === 'number') {
                // 如果上下两侧方块相同，排除该索引
                if (grid[row-1][col].imageIndex === grid[row+1][col].imageIndex) {
                  validIndices = validIndices.filter(idx => idx !== grid[row-1][col].imageIndex);
                }
              }
            }
            
            // 如果没有有效的索引，使用任意不同的索引
            let newIndex;
            if (validIndices.length === 0) {
              do {
                newIndex = Math.floor(Math.random() * imageUrls.length);
              } while (newIndex === currentIndex);
            } else {
              // 从有效索引中随机选择
              newIndex = validIndices[Math.floor(Math.random() * validIndices.length)];
            }
            
            // 修改方块
            grid[row][col].imageIndex = newIndex;
            grid[row][col].imageUrl = imageUrls[newIndex];
          }
        }
      });
      
      // 重新检查匹配
      matches = this.findMatches(grid);
    }
    
    // 如果尝试多次后仍有匹配，使用更激进的方法
    if (matches.length > 0) {
      console.log('尝试修复匹配失败，使用更激进的方法...');
      
      // 对每个匹配的方块，直接修改为随机图片
      matches.forEach(match => {
        const { row, col } = match;
        if (grid[row] && grid[row][col]) {
          const currentIndex = grid[row][col].imageIndex;
          let newIndex;
          do {
            newIndex = Math.floor(Math.random() * imageUrls.length);
          } while (newIndex === currentIndex);
          
          grid[row][col].imageIndex = newIndex;
          grid[row][col].imageUrl = imageUrls[newIndex];
        }
      });
    }
    
    return grid;
  },
  
  // 找出匹配组
  findMatchGroups: function(matches) {
    if (!matches || !Array.isArray(matches) || matches.length === 0) return [];
    
    let groups = [];
    let visited = {};
    
    // 对每个匹配的方块
    matches.forEach(match => {
      const key = `${match.row}-${match.col}`;
      if (visited[key]) return; // 如果已经访问过，跳过
      
      // 找出所有相连的方块
      let group = [match];
      visited[key] = true;
      
      // 检查水平方向
      let j = match.col + 1;
      while (j < this.data.gridSize) {
        const nextKey = `${match.row}-${j}`;
        const nextMatch = matches.find(m => m.row === match.row && m.col === j);
        if (nextMatch && !visited[nextKey]) {
          group.push(nextMatch);
          visited[nextKey] = true;
          j++;
        } else {
          break;
        }
      }
      
      j = match.col - 1;
      while (j >= 0) {
        const nextKey = `${match.row}-${j}`;
        const nextMatch = matches.find(m => m.row === match.row && m.col === j);
        if (nextMatch && !visited[nextKey]) {
          group.push(nextMatch);
          visited[nextKey] = true;
          j--;
        } else {
          break;
        }
      }
      
      // 检查垂直方向
      let i = match.row + 1;
      while (i < this.data.gridSize) {
        const nextKey = `${i}-${match.col}`;
        const nextMatch = matches.find(m => m.row === i && m.col === match.col);
        if (nextMatch && !visited[nextKey]) {
          group.push(nextMatch);
          visited[nextKey] = true;
          i++;
        } else {
          break;
        }
      }
      
      i = match.row - 1;
      while (i >= 0) {
        const nextKey = `${i}-${match.col}`;
        const nextMatch = matches.find(m => m.row === i && m.col === match.col);
        if (nextMatch && !visited[nextKey]) {
          group.push(nextMatch);
          visited[nextKey] = true;
          i--;
        } else {
          break;
        }
      }
      
      // 添加到匹配组
      if (group.length >= 3) {
        groups.push(group);
      }
    });
    
    return groups;
  },

  startGameTimer: function() {
    console.log('开始游戏计时器');
    
    // 确保清除任何存在的游戏计时器
    if (this.gameTimer) {
      clearInterval(this.gameTimer);
      this.gameTimer = null;
    }
    
    this.gameTimer = setInterval(() => {
      // 检查游戏状态，防止在游戏结束后继续运行
      if (this.data.gameOver || !this.data.isPlaying) {
        console.log('游戏已结束或未在进行中，停止计时器');
        clearInterval(this.gameTimer);
        this.gameTimer = null;
        return;
      }
      
      let timeLeft = this.data.timeLeft - 1;
      console.log('剩余时间:', timeLeft);
      
      if (timeLeft <= 0) {
        console.log('时间到，游戏结束');
        clearInterval(this.gameTimer);
        this.gameTimer = null;
        this.gameOver();
        return;
      }
      
      this.setData({ timeLeft });
    }, 1000);
  },

  // 开始触摸（拖拽开始）
  onTouchStart: function(e) {
    if (!this.data.isPlaying || this.data.gameOver) return;
    
    const touch = e.touches[0];
    const { row, col } = e.currentTarget.dataset;
    
    this.setData({
      isDragging: false, // 初始不设为拖拽状态
      dragStartCell: { row: parseInt(row), col: parseInt(col) },
      dragCurrentCell: null,
      touchStartX: touch.pageX,
      touchStartY: touch.pageY,
      touchStartTime: Date.now(), // 记录触摸开始时间
      selectedCell: { row: parseInt(row), col: parseInt(col) } // 显示选中效果
    });
  },

  // 触摸移动（拖拽过程）
  onTouchMove: function(e) {
    if (!this.data.isPlaying || this.data.gameOver || !this.data.dragStartCell) return;
    
    const touch = e.touches[0];
    const { touchStartX, touchStartY, cellSize } = this.data;
    
    // 计算移动距离
    const deltaX = touch.pageX - touchStartX;
    const deltaY = touch.pageY - touchStartY;
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    
    // 如果移动距离超过阈值，开始拖拽
    if (distance > 20 && !this.data.isDragging) {
      this.setData({ isDragging: true });
    }
    
    if (this.data.isDragging) {
      // 根据移动方向计算目标方块
      const { dragStartCell } = this.data;
      let targetRow = dragStartCell.row;
      let targetCol = dragStartCell.col;
      
      // 判断主要移动方向
      if (Math.abs(deltaX) > Math.abs(deltaY)) {
        // 水平移动
        if (deltaX > cellSize / 2 && dragStartCell.col < 7) {
          targetCol = dragStartCell.col + 1;
        } else if (deltaX < -cellSize / 2 && dragStartCell.col > 0) {
          targetCol = dragStartCell.col - 1;
        }
      } else {
        // 垂直移动
        if (deltaY > cellSize / 2 && dragStartCell.row < 7) {
          targetRow = dragStartCell.row + 1;
        } else if (deltaY < -cellSize / 2 && dragStartCell.row > 0) {
          targetRow = dragStartCell.row - 1;
        }
      }
      
      // 更新当前拖拽目标
      const newDragCurrentCell = { row: targetRow, col: targetCol };
      if (!this.data.dragCurrentCell || 
          this.data.dragCurrentCell.row !== targetRow || 
          this.data.dragCurrentCell.col !== targetCol) {
        this.setData({ 
          dragCurrentCell: newDragCurrentCell,
          selectedCell: newDragCurrentCell // 更新选中状态以显示视觉反馈
        });
      }
    }
  },

  // 结束触摸（拖拽结束）
  onTouchEnd: function(e) {
    if (!this.data.isPlaying || this.data.gameOver) return;
    
    const { isDragging, dragStartCell, dragCurrentCell, touchStartTime } = this.data;
    const touchDuration = Date.now() - (touchStartTime || 0);
    
    if (isDragging && dragStartCell && dragCurrentCell) {
      // 检查是否是相邻的方块
      const isAdjacent = (
        (Math.abs(dragStartCell.row - dragCurrentCell.row) === 1 && dragStartCell.col === dragCurrentCell.col) ||
        (Math.abs(dragStartCell.col - dragCurrentCell.col) === 1 && dragStartCell.row === dragCurrentCell.row)
      );
      
      if (isAdjacent && !(dragStartCell.row === dragCurrentCell.row && dragStartCell.col === dragCurrentCell.col)) {
        // 执行交换
        this.swapCells(dragStartCell.row, dragStartCell.col, dragCurrentCell.row, dragCurrentCell.col);
      } else {
        // 没有有效移动，清除选中状态
        this.setData({ selectedCell: null });
      }
    } else if (!isDragging && dragStartCell && touchDuration < 500) {
      // 如果没有拖拽且触摸时间较短，标记为点击事件
      this.setData({ 
        isClickEvent: true,
        clickRow: dragStartCell.row,
        clickCol: dragStartCell.col
      });
      
      // 延迟处理点击事件，避免与tap事件冲突
      setTimeout(() => {
        if (this.data.isClickEvent) {
          this.handleCellClick(this.data.clickRow, this.data.clickCol);
          this.setData({ isClickEvent: false });
        }
      }, 50);
    }
    
    // 重置拖拽状态
    this.setData({
      isDragging: false,
      dragStartCell: null,
      dragCurrentCell: null,
      touchStartX: 0,
      touchStartY: 0,
      touchStartTime: 0
    });
  },

  // 处理点击逻辑（原有的selectCell逻辑）
  handleCellClick: function(row, col) {
    const { selectedCell } = this.data;
    
    // 如果没有选中的方块，选中当前方块
    if (!selectedCell) {
      this.setData({ selectedCell: { row, col } });
      return;
    }
    
    // 如果点击的是已选中的方块，取消选中
    if (selectedCell.row === row && selectedCell.col === col) {
      this.setData({ selectedCell: null });
      return;
    }
    
    // 检查是否是相邻的方块
    const isAdjacent = (
      (Math.abs(selectedCell.row - row) === 1 && selectedCell.col === col) ||
      (Math.abs(selectedCell.col - col) === 1 && selectedCell.row === row)
    );
    
    if (isAdjacent) {
      // 交换方块
      this.swapCells(selectedCell.row, selectedCell.col, row, col);
    } else {
      // 如果不相邻，选中新的方块
      this.setData({ selectedCell: { row, col } });
    }
  },

  selectCell: function(e) {
    // 检查是否已经被触摸事件处理过了
    if (this.data.isClickEvent) {
      // 清除标记，避免重复处理
      this.setData({ isClickEvent: false });
      return;
    }
    
    if (!this.data.isPlaying || this.data.gameOver) return;
    
    const { row, col } = e.currentTarget.dataset;
    this.handleCellClick(parseInt(row), parseInt(col));
  },

  swapCells: function(row1, col1, row2, col2) {
    const { grid } = this.data;
    
    // 检查单元格是否有效
    if (!grid[row1] || !grid[row1][col1] || !grid[row2] || !grid[row2][col2]) {
      console.error('无效的单元格位置:', row1, col1, row2, col2);
      this.setData({ selectedCell: null });
      return;
    }
    
    // 创建网格副本
    let newGrid = JSON.parse(JSON.stringify(grid));
    
    // 交换方块
    const temp = { ...newGrid[row1][col1] };
    newGrid[row1][col1] = { ...newGrid[row2][col2], row: row1, col: col1 };
    newGrid[row2][col2] = { ...temp, row: row2, col: col2 };
    
    // 检查交换后是否有匹配
    const matches = this.findMatches(newGrid);
    
    if (matches.length > 0) {
      // 如果有匹配，更新网格并处理匹配
      this.setData({ 
        grid: newGrid,
        selectedCell: null
      });
      
      // 播放交换音效
      this.playSound('swap');
      
      // 处理匹配
      setTimeout(() => {
        this.handleMatches(matches);
      }, 300);
    } else {
      // 如果没有匹配，交换回来
      this.setData({ selectedCell: null });
      
      // 播放错误音效
      this.playSound('error');
      
      // 显示交换动画然后交换回来
      this.setData({ grid: newGrid });
      
      setTimeout(() => {
        let originalGrid = JSON.parse(JSON.stringify(grid)); // 使用原始网格而不是newGrid
        this.setData({ grid: originalGrid });
      }, 500);
    }
  },

  findMatches: function(grid) {
    if (!grid || !Array.isArray(grid)) {
      console.error('无效的网格数据');
      return [];
    }
    
    const gridSize = grid.length;
    let matches = [];
    
    // 检查水平匹配
    for (let i = 0; i < gridSize; i++) {
      if (!grid[i] || !Array.isArray(grid[i])) continue;
      
      let j = 0;
      while (j <= gridSize - 3) { // 修复：改为 <= gridSize - 3，确保j+2不会越界
        // 确保所有单元格都有有效的imageIndex
        if (grid[i][j] && grid[i][j+1] && grid[i][j+2] && 
            typeof grid[i][j].imageIndex === 'number' && 
            typeof grid[i][j+1].imageIndex === 'number' && 
            typeof grid[i][j+2].imageIndex === 'number') {
          
          // 检查是否有三个相同的图标
          if (grid[i][j].imageIndex === grid[i][j+1].imageIndex &&
              grid[i][j].imageIndex === grid[i][j+2].imageIndex) {
            
            // 找到水平匹配的三个或更多
            let matchLength = 3;
            while (j + matchLength < gridSize && 
                   grid[i][j + matchLength] && 
                   typeof grid[i][j + matchLength].imageIndex === 'number' &&
                   grid[i][j].imageIndex === grid[i][j+matchLength].imageIndex) {
              matchLength++;
            }
            
            // 添加所有匹配的方块
            for (let k = 0; k < matchLength; k++) {
              // 检查是否已经添加过这个方块
              const existingMatch = matches.find(m => m.row === i && m.col === j + k);
              if (!existingMatch) {
                matches.push({ row: i, col: j + k });
              }
            }
            
            j += matchLength; // 跳过已匹配的方块
          } else {
            j++;
          }
        } else {
          j++;
        }
      }
    }
    
    // 检查垂直匹配
    for (let j = 0; j < gridSize; j++) {
      let i = 0;
      while (i <= gridSize - 3) { // 修复：改为 <= gridSize - 3，确保i+2不会越界
        // 确保所有单元格都有有效的imageIndex
        if (grid[i] && grid[i+1] && grid[i+2] && 
            grid[i][j] && grid[i+1][j] && grid[i+2][j] &&
            typeof grid[i][j].imageIndex === 'number' && 
            typeof grid[i+1][j].imageIndex === 'number' && 
            typeof grid[i+2][j].imageIndex === 'number') {
          
          // 检查是否有三个相同的图标
          if (grid[i][j].imageIndex === grid[i+1][j].imageIndex &&
              grid[i][j].imageIndex === grid[i+2][j].imageIndex) {
            
            // 找到垂直匹配的三个或更多
            let matchLength = 3;
            while (i + matchLength < gridSize && 
                   grid[i + matchLength] && 
                   grid[i + matchLength][j] &&
                   typeof grid[i + matchLength][j].imageIndex === 'number' &&
                   grid[i][j].imageIndex === grid[i+matchLength][j].imageIndex) {
              matchLength++;
            }
            
            // 添加所有匹配的方块
            for (let k = 0; k < matchLength; k++) {
              // 检查是否已经添加过这个方块
              const existingMatch = matches.find(m => m.row === i + k && m.col === j);
              if (!existingMatch) {
                matches.push({ row: i + k, col: j });
              }
            }
            
            i += matchLength; // 跳过已匹配的方块
          } else {
            i++;
          }
        } else {
          i++;
        }
      }
    }
    
    // 如果找到匹配，打印详细信息
    if (matches.length > 0) {
      console.log(`找到 ${matches.length} 个匹配的方块:`);
      matches.forEach((match, index) => {
        const { row, col } = match;
        if (grid[row] && grid[row][col]) {
          console.log(`匹配 ${index+1}: 位置(${row},${col}), 图片索引: ${grid[row][col].imageIndex}`);
        }
      });
    }
    
    // 去重
    let uniqueMatches = [];
    let matchMap = {};
    
    for (let match of matches) {
      const key = `${match.row}-${match.col}`;
      if (!matchMap[key]) {
        matchMap[key] = true;
        uniqueMatches.push(match);
      }
    }
    
    return uniqueMatches;
  },

  handleMatches: function(matches) {
    if (matches.length === 0) return;
    
    console.log(`处理 ${matches.length} 个匹配的方块`);
    
    const { grid, score, comboCount, maxCombo } = this.data;
    let newGrid = JSON.parse(JSON.stringify(grid));
    
    // 计算得分
    const baseScore = matches.length * 10;
    const newComboCount = comboCount + 1;
    
    // 连击奖励计算：连击越多，奖励越高
    let comboMultiplier = 1;
    let comboBonus = 0;
    
    if (newComboCount > 1) {
      comboMultiplier = Math.min(newComboCount * 0.5 + 0.5, 3); // 最大3倍
      comboBonus = Math.floor(newComboCount * newComboCount * 5); // 连击额外奖励
    }
    
    const totalScore = score + Math.floor(baseScore * comboMultiplier) + comboBonus;
    const newMaxCombo = Math.max(maxCombo, newComboCount);
    
    // 更新游戏状态
    this.setData({
      score: totalScore,
      comboCount: newComboCount,
      comboBonus: comboBonus,
      maxCombo: newMaxCombo,
      showCombo: newComboCount > 1
    });
    
    // 连击显示时间根据连击数调整
    if (newComboCount > 1) {
      const showTime = Math.min(2000 + newComboCount * 200, 3500); // 最长3.5秒
      setTimeout(() => {
        if (this.data.showCombo && this.data.comboCount === newComboCount) {
          this.setData({ showCombo: false });
        }
      }, showTime);
    }
    
    // 播放消除音效（连击时音效不同）
    this.playSound(newComboCount > 1 ? 'combo' : 'match');
    
    // 标记要消除的方块
    for (let match of matches) {
      if (newGrid[match.row] && newGrid[match.row][match.col]) {
        newGrid[match.row][match.col].matched = true;
        console.log(`标记方块 (${match.row},${match.col}) 为已匹配`);
      }
    }
    
    this.setData({ grid: newGrid, animations: matches });
    
    // 延迟后移除匹配的方块并填充新方块
    setTimeout(() => {
      this.removeMatches();
    }, 300);
  },

  removeMatches: function() {
    const { grid, gridSize, imageUrls } = this.data;
    let newGrid = JSON.parse(JSON.stringify(grid));
    
    console.log("开始移除匹配的方块");
    
    // 对每一列进行处理
    for (let col = 0; col < gridSize; col++) {
      // 找出该列中所有被匹配的方块
      let matchedCells = [];
      for (let row = 0; row < gridSize; row++) {
        if (newGrid[row] && newGrid[row][col] && newGrid[row][col].matched) {
          matchedCells.push(row);
        }
      }
      
      // 如果该列有被匹配的方块
      if (matchedCells.length > 0) {
        console.log(`列 ${col} 有 ${matchedCells.length} 个匹配的方块:`, matchedCells);
        
        // 从下往上移动方块
        for (let row = gridSize - 1; row >= 0; row--) {
          if (newGrid[row] && newGrid[row][col] && newGrid[row][col].matched) {
            console.log(`处理匹配的方块 (${row},${col})`);
            
            // 找到上方最近的未匹配方块
            let sourceRow = row - 1;
            while (sourceRow >= 0 && 
                  (newGrid[sourceRow] === undefined || 
                   newGrid[sourceRow][col] === undefined || 
                   newGrid[sourceRow][col].matched)) {
              sourceRow--;
            }
            
            if (sourceRow >= 0) {
              // 将上方方块移到当前位置
              console.log(`将方块从 (${sourceRow},${col}) 移动到 (${row},${col})`);
              newGrid[row][col] = { 
                ...newGrid[sourceRow][col],
                row: row,
                col: col
              };
              newGrid[sourceRow][col].matched = true; // 标记原位置为已匹配
            } else {
              // 如果上方没有未匹配方块，生成新方块
              const imageIndex = Math.floor(Math.random() * imageUrls.length);
              console.log(`在位置 (${row},${col}) 生成新方块，图片索引: ${imageIndex}`);
              newGrid[row][col] = {
                imageUrl: imageUrls[imageIndex],
                imageIndex: imageIndex,
                row: row,
                col: col,
                id: `cell-${row}-${col}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, // 确保ID唯一
                isNew: true // 标记为新方块
              };
            }
          }
        }
      }
    }
    
    // 更新网格
    this.setData({ 
      grid: newGrid,
      animations: []
    });
    
    // 检查是否有新的匹配
    setTimeout(() => {
      // 移除新方块标记
      let finalGrid = JSON.parse(JSON.stringify(newGrid));
      for (let i = 0; i < gridSize; i++) {
        for (let j = 0; j < gridSize; j++) {
          if (finalGrid[i] && finalGrid[i][j]) {
            if (finalGrid[i][j].isNew) {
              delete finalGrid[i][j].isNew;
            }
            if (finalGrid[i][j].matched) {
              delete finalGrid[i][j].matched;
            }
          }
        }
      }
      
      this.setData({ grid: finalGrid });
      
      // 检查新的匹配
      const newMatches = this.findMatches(finalGrid);
      if (newMatches.length > 0) {
        console.log(`移除匹配后发现新的匹配: ${newMatches.length} 个`);
        this.handleMatches(newMatches);
      } else {
        console.log("没有新的匹配");
        // 如果没有新的匹配，重置连击计数并隐藏连击提示
        this.setData({ 
          comboCount: 0,
          showCombo: false,
          comboBonus: 0
        });
        
        // 检查是否有可行的移动
        if (!this.hasValidMoves(finalGrid)) {
          // 如果没有可行的移动，重新生成网格
          console.log("没有可行的移动，重新洗牌");
          this.reshuffleGrid();
        }
      }
    }, 500);
  },

  hasValidMoves: function(grid) {
    const { gridSize } = this.data;
    
    // 检查每个位置的水平和垂直交换是否会产生匹配
    for (let i = 0; i < gridSize; i++) {
      for (let j = 0; j < gridSize; j++) {
        // 确保当前单元格有效
        if (!grid[i] || !grid[i][j]) continue;
        
        // 检查水平交换
        if (j < gridSize - 1 && grid[i] && grid[i][j+1]) {
          // 创建交换后的网格
          let testGrid = JSON.parse(JSON.stringify(grid));
          const temp = { ...testGrid[i][j] };
          testGrid[i][j] = { ...testGrid[i][j+1], row: i, col: j };
          testGrid[i][j+1] = { ...temp, row: i, col: j+1 };
          
          // 检查是否有匹配
          if (this.findMatches(testGrid).length > 0) {
            return true;
          }
        }
        
        // 检查垂直交换
        if (i < gridSize - 1 && grid[i+1] && grid[i+1][j]) {
          // 创建交换后的网格
          let testGrid = JSON.parse(JSON.stringify(grid));
          const temp = { ...testGrid[i][j] };
          testGrid[i][j] = { ...testGrid[i+1][j], row: i, col: j };
          testGrid[i+1][j] = { ...temp, row: i+1, col: j };
          
          // 检查是否有匹配
          if (this.findMatches(testGrid).length > 0) {
            return true;
          }
        }
      }
    }
    
    return false;
  },

  reshuffleGrid: function() {
    // 显示重新洗牌提示
    this.setData({ reshuffling: true });
    
    // 播放洗牌音效
    this.playSound('shuffle');
    
    // 延迟后重新生成网格
    setTimeout(() => {
      this.initGrid();
      this.setData({ reshuffling: false });
    }, 1000);
  },

  playSound: function(type) {
    // 根据不同类型播放不同的震动效果
    switch(type) {
      case 'combo':
        // 连击时的强烈震动
        wx.vibrateShort({
          type: 'heavy'
        });
        break;
      case 'match':
        // 普通消除的轻微震动
        wx.vibrateShort({
          type: 'light'
        });
        break;
      case 'swap':
        // 交换时的中等震动
        wx.vibrateShort({
          type: 'medium'
        });
        break;
      case 'error':
        // 错误时的震动
        wx.vibrateShort({
          type: 'heavy'
        });
        break;
      case 'shuffle':
        // 洗牌时的震动
        wx.vibrateShort({
          type: 'medium'
        });
        break;
      default:
        wx.vibrateShort({
          type: 'light'
        });
    }
    
    // 音效播放代码（如果需要）
    /*
    const audioContext = wx.createInnerAudioContext();
    
    switch(type) {
      case 'match':
        audioContext.src = '/audio/match.mp3';
        break;
      case 'combo':
        audioContext.src = '/audio/combo.mp3';
        break;
      case 'swap':
        audioContext.src = '/audio/swap.mp3';
        break;
      case 'error':
        audioContext.src = '/audio/error.mp3';
        break;
      case 'shuffle':
        audioContext.src = '/audio/shuffle.mp3';
        break;
    }
    
    audioContext.play();
    */
  },

  gameOver: function() {
    console.log('游戏结束函数被调用');
    
    // 立即清除所有定时器，防止继续运行
    if (this.gameTimer) {
      clearInterval(this.gameTimer);
      this.gameTimer = null;
      console.log('在gameOver中清除gameTimer');
    }
    
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
      this.countdownTimer = null;
      console.log('在gameOver中清除countdownTimer');
    }
    
    // 立即设置游戏结束状态，防止重复触发
    if (this.data.gameOver) {
      console.log('游戏已经结束，防止重复处理');
      return;
    }
    
    // 添加游戏结束动画
    this.setData({ 
      gameOverAnimation: true,
      isPlaying: false // 立即停止游戏
    });
    
    // 延迟显示游戏结束界面
    setTimeout(() => {
      console.log('设置游戏结束状态');
      this.setData({ 
        gameOver: true,
        isPlaying: false,
        gameOverAnimation: false
      });
      
      console.log('gameOver 状态已设置为:', this.data.gameOver);
      
      // 更新最高分
      if (this.data.score > this.data.highScore) {
        this.setData({ 
          highScore: this.data.score,
          newRecord: true
        });
        wx.setStorageSync('matchHighScore', this.data.score);
        
        // 3秒后隐藏新纪录提示
        setTimeout(() => {
          if (this.data.newRecord) { // 只在状态仍为true时才隐藏
            this.setData({ newRecord: false });
          }
        }, 3000);
      }
    }, 1500);
  },

  restartGame: function() {
    console.log('重新开始游戏被调用');
    
    // 清除所有定时器
    if (this.gameTimer) {
      clearInterval(this.gameTimer);
      this.gameTimer = null;
      console.log('清除gameTimer');
    }
    
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
      this.countdownTimer = null;
      console.log('清除countdownTimer');
    }
    
    // 完全重置游戏状态
    this.setData({
      gameOver: false,
      isPlaying: false, // 确保重置为false
      gameStarted: true, // 重新开始时也要保持游戏已开始状态
      newRecord: false,
      gameOverAnimation: false,
      score: 0,
      timeLeft: 60,
      countdown: 0,
      comboCount: 0,
      showCombo: false,
      comboBonus: 0,
      selectedCell: null, // 清除选中状态
      isDragging: false,
      dragStartCell: null,
      dragCurrentCell: null,
      grid: [] // 清空网格
    });
    
    console.log('游戏状态已重置');
    
    // 延迟启动新游戏，确保状态完全清除
    setTimeout(() => {
      this.startGame();
    }, 100);
  },

  onShareAppMessage: function() {
    return {
      title: '一二布布消消乐，我的最高分是' + this.data.highScore + '分！快来挑战吧！',
      path: '/pages/game/game'
    };
  },
  
  onUnload: function() {
    // 清除定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
    if (this.gameTimer) {
      clearInterval(this.gameTimer);
    }
  },

  // 防止iOS系统的意外滚动
  preventTouchMove: function(e) {
    // 阻止默认的触摸移动行为，防止iOS系统的滚动
    e.preventDefault();
    return false;
  }
})
